package com.cmcc.sdtp.sdtp.message;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.cmcc.sdtp.util.SDTPFactory;
import com.cmcc.xdr.message.SingleSigMsg;

/**
 * @comments 一个关于线程以及单例和那些我不会写的东西
 * @author B
 * @date Nov-12-2015
 * @version 1.0
 */
public final class JJJJManageForComposedReg extends Thread {

	private static Logger logger = LogManager.getLogger(JJJJManageForComposedReg.class);
	/**
	 * @content 单例模式静态内部类,延迟加载同时保证高并发时不会重复初始化
	 * 
	 * @author B
	 * 
	 */
	private static class SingletonHolder {
		private static final JJJJManageForComposedReg INSTANCE = new JJJJManageForComposedReg();
		static {
			INSTANCE.start();
		}
	}

	private transient final List<SingleSigMsg> SSGList; // sip
	private final int batchSize = 1000;

	private JJJJManageForComposedReg() {
		SSGList = Collections.synchronizedList(new ArrayList<SingleSigMsg>(batchSize));
	}

	/**
	 * 
	 * @comments 单例模式获取实例
	 * @return
	 * @version 1.0
	 */
	public static JJJJManageForComposedReg getInstance() {
		return SingletonHolder.INSTANCE;
	}

	@Override
	public void run() {
		sendAll();
	}

	private void sendAll() {
		while (true) {
			try {
				if (SSGList.size() > 0) {
					if(SSGList.size() > 20000){
						logger.info("SSGList.size()超过2W数据量 :"+SSGList.size());
					}
					send(SSGList);
				} else {
					// 列表中没有消息，等待一秒
					Thread.sleep(1000);
					// LOGGER.debug("空闲中");
					continue;
				}
				Thread.sleep(300);
			} catch (Exception e) {
				logger.error("调用入库发生异常：",e);
				// LOGGER.info("发送过程中发生错误", e);
			}
		}
	}

	private void send(final List<SingleSigMsg> list) {
		synchronized (list) {
			List<SingleSigMsg> saveList = new ArrayList<SingleSigMsg>();
			saveList = new ArrayList<SingleSigMsg>();
			saveList.addAll(list);
			list.clear();

			try {
//				SaveSdtpInfo.save(saveList);
				SDTPFactory.saveSdtpInfo(saveList);
			} catch (Exception e) {
				logger.error("save 方法发生异常："+saveList+e.getStackTrace());
			}
		}//同步块减少处理过程，能否提高XDR处理？
	}


	/**
	 * @comments 添加单条记录通用方法
	 * @param info要插入的单条记录
	 * @see
	 * @version 1.0
	 */
	public void addToList(final SingleSigMsg info) {
		// 插入到list
		synchronized (SSGList) {
			SSGList.add(info);
		}
	}

}